package com.eaero.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eaero.CommonResp;
import com.eaero.entity.TraceTool;
import com.eaero.entity.TraceToolStock;
import com.eaero.entity.TraceToolStockDetail;
import com.eaero.entity.TraceUser;
import com.eaero.mapper.TraceToolStockMapper;
import com.eaero.service.ITraceToolService;
import com.eaero.service.ITraceToolStockDetailService;
import com.eaero.service.ITraceToolStockService;
import com.eaero.service.ITraceUserService;
import com.eaero.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Ye Zhihong
 * @description 针对表【trace_tool_stock】的数据库操作Service实现
 * @createDate 2023-03-17 16:24:50
 */
@Service
public class TraceToolStockServiceImpl extends ServiceImpl<TraceToolStockMapper, TraceToolStock>
        implements ITraceToolStockService {

    @Autowired
    private ITraceToolStockDetailService traceToolStockDetailService;
    @Autowired
    private ITraceToolService traceToolService;
    @Autowired
    private ITraceUserService traceUserService;

    /**
     * 获取工具盘点单信息
     *
     * @param request
     * @return
     */
    @Override
    public CommonResp getToolStock(ToolStockRequest request) {
        if (StrUtil.isAllEmpty(request.getStatus(), request.getStockPnum(), request.getCreated(), request.getOrigin(),
                request.getWarehouse(), request.getCreatedUser())) {
            return CommonResp.buildFailMsg("库存信息获取失败！");
        }

        List<TraceToolStock> traceToolStocks = getBaseMapper().selectList(Wrappers.<TraceToolStock>lambdaQuery()
                .select(TraceToolStock::getStatus, TraceToolStock::getRemark, TraceToolStock::getUpdated, TraceToolStock::getCreated, TraceToolStock::getPnum,
                        TraceToolStock::getOrigin, TraceToolStock::getUpdatedUser, TraceToolStock::getWarehouse, TraceToolStock::getCreatedUser)
                .like(StrUtil.isNotBlank(request.getStockPnum()), TraceToolStock::getPnum, request.getStockPnum())
                .like(StrUtil.isNotBlank(request.getWarehouse()), TraceToolStock::getWarehouse, request.getWarehouse())
                .like(StrUtil.isNotBlank(request.getCreatedUser()), TraceToolStock::getCreatedUser, request.getCreatedUser())
                .like(StrUtil.isNotBlank(request.getCreated()), TraceToolStock::getCreated, request.getCreated())
                .like(StrUtil.isNotBlank(request.getStatus()), TraceToolStock::getStatus, request.getStatus())
                .like(StrUtil.isNotBlank(request.getOrigin()), TraceToolStock::getOrigin, request.getOrigin())
                .orderByDesc(TraceToolStock::getTsId)
        );

        return CommonResp.buildSucsDataListMsg(traceToolStocks, "数据获取成功！");
    }

    /**
     * 根据盘点单号获取工具盘点单明细
     *
     * @param request
     * @return
     */
    @Override
    public CommonResp getToolStockDetail(ToolStockRequest request) {
        if (StrUtil.isBlank(request.getStockPnum())) {
            return CommonResp.buildFailMsg("库存信息获取失败！");
        }
        List<TraceToolStockDetail> list = traceToolStockDetailService.list(Wrappers.<TraceToolStockDetail>lambdaQuery().eq(TraceToolStockDetail::getStockPnum, request.getStockPnum()));
        if (CollUtil.isEmpty(list)) {
            return CommonResp.buildFailMsg("没有该盘点单明细信息");
        }
        return CommonResp.buildSucsDataListMsg(list, "数据获取成功！");
    }

    @Override
    public CommonResp goTlStock(GoTlStockRequest request) {
        TraceToolStock traceToolStock = new TraceToolStock();
        List<TraceUser> traceUserList = traceUserService.list();
        Map<String, String> userCodeToNameMap = traceUserList.stream().collect(Collectors.toMap(TraceUser::getUserCode, TraceUser::getUserName));
        String sp = System.currentTimeMillis() + "";
        traceToolStock.setPnum(sp);
        traceToolStock.setCreatedUser(request.getUserCode() + " " + StrUtil.emptyToNull(userCodeToNameMap.get(request.getUserCode())));
        traceToolStock.setCreated(DateUtil.format(new Date(), "yyyy-MM-dd"));
        traceToolStock.setUpdatedUser(request.getUserCode());
        traceToolStock.setUpdated(DateUtil.format(new Date(), "yyyy-MM-dd"));
        traceToolStock.setRemark(request.getRemark());
        //开放/盘点中/关闭/作废
        traceToolStock.setStatus("开放");
        traceToolStock.setOrigin(request.getOrigin());
        traceToolStock.setWarehouse(request.getWarehouse());
        traceToolStock.setUserCode(request.getUserCode());
        boolean save = this.save(traceToolStock);
        if (save) {
            List<Storesloc> newStockList = request.getNewStock();
            Set<String> storeslocList = newStockList.stream().map(Storesloc::getStoresloc).collect(Collectors.toSet());
            List<TraceTool> toolList = traceToolService.list(Wrappers.<TraceTool>lambdaQuery()
                    .eq(TraceTool::getWarehouse, request.getWarehouse())
                    .in(TraceTool::getStoresloc, storeslocList)
            );
            List<TraceToolStockDetail> traceToolStockDetailList = new ArrayList<>();
            for (TraceTool tool : toolList) {
                TraceToolStockDetail traceToolStockDetail = new TraceToolStockDetail();
                traceToolStockDetail.setTsId(traceToolStock.getTsId());
                traceToolStockDetail.setStockPnum(sp);
                traceToolStockDetail.setWarehouse(request.getWarehouse());
                traceToolStockDetail.setPartno(tool.getPartno());
                traceToolStockDetail.setSerialno(tool.getTrno());
                traceToolStockDetail.setStoresloc(tool.getStoresloc());
                traceToolStockDetail.setCheckStatus(tool.getTlStatus());
                traceToolStockDetail.setStatus("开放");
                traceToolStockDetail.setTlFlag(tool.getTlFlag());
                traceToolStockDetail.setImgFlag(tool.getImgFlag());
                traceToolStockDetail.setRid(tool.getRid());
                traceToolStockDetail.setUnitofmeas(tool.getUnitofmeas());
                traceToolStockDetail.setBarcode(tool.getBarcode());
                traceToolStockDetail.setRfidId(tool.getRfidId());
                traceToolStockDetail.setParentPartno(tool.getParentPartno());
                traceToolStockDetail.setParentTrno(tool.getParentTrno());
                traceToolStockDetail.setWhseDesc(tool.getWhseDesc());
                traceToolStockDetail.setChildNum(tool.getChildNum() + "");
                traceToolStockDetail.setMeasuringNo(tool.getMeasuringNo());
                traceToolStockDetail.setStandByPn(tool.getStandByPn());
                traceToolStockDetail.setPartdescr(tool.getPartdescr());
                traceToolStockDetail.setCatalogueType(tool.getCatalogueType());
                traceToolStockDetail.setTlStatus(tool.getTlStatus());
                traceToolStockDetailList.add(traceToolStockDetail);
            }
            traceToolStockDetailService.saveBatch(traceToolStockDetailList);
            return CommonResp.buildSuccessMsg("生成盘点单成功！" + sp);
        }
        return CommonResp.buildFailMsg("生成盘点单失败！");
    }

    @Override
    public CommonResp CancelTlStock(CancelTlStockRequest request) {
        List<StockPnumVo> stockPnumVoList = request.getCancelStock();
        Set<String> stockPNumList = stockPnumVoList.stream().map(StockPnumVo::getStockPnum).collect(Collectors.toSet());
        boolean re = this.update(Wrappers.<TraceToolStock>lambdaUpdate()
                .set(TraceToolStock::getCancellationc, "0")
                .set(TraceToolStock::getStatus, "作废")
                .in(TraceToolStock::getPnum, stockPNumList));
        if (re) {
            return CommonResp.buildSuccessMsg("作废成功!");
        }
        return CommonResp.buildSuccessMsg("作废失败!");
    }

    @Override
    public CommonResp DoTlStockRequest(DoTlStockRequest request) {
        List<DoStockVo> doStockVoList = request.getDoStock();
        List<Integer> tsdIdList = doStockVoList.stream().map(stockVo -> Integer.parseInt(stockVo.getTsdId())).collect(Collectors.toList());
        List<TraceToolStockDetail> stockDetailList = traceToolStockDetailService.list(Wrappers.<TraceToolStockDetail>lambdaQuery()
                .in(TraceToolStockDetail::getTsdId, tsdIdList)
        );
        List<TraceToolStockDetail> updateList = new ArrayList<>();
        for (TraceToolStockDetail traceToolStockDetail : stockDetailList) {
            for (DoStockVo doStockVo : doStockVoList) {
                if (StrUtil.equals(traceToolStockDetail.getTsdId() + "", doStockVo.getTsdId())) {
                    traceToolStockDetail.setCheckRemark(doStockVo.getCheckRemark());
                    traceToolStockDetail.setCheckStatus(doStockVo.getStatus());
                    traceToolStockDetail.setCheckDate(DateUtil.now());
                    updateList.add(traceToolStockDetail);
                }
            }
        }
        boolean re = traceToolStockDetailService.updateBatchById(updateList);
        if (re) {
            return CommonResp.buildSuccessMsg("盘点成功!");
        }
        return CommonResp.buildSuccessMsg("盘点失败!");
    }
}




